package com.omesoft.hksnore.util.photo;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Omesoft on 2016/11/30.
 */

public class DownPhotoUtil {
    private byte[] dataImage;
    Bitmap bitmap = null;
    public static final String downUrl = "http://snorekiller.omesoft.com/Upload/member_photos/";

    public DownPhotoUtil() {

    }

    /**
     * 联网下载图片
     */
    private Bitmap downloadPhoto(final File file, final String urlPath, final String name) {

        try {
//            MyThread.startNewThread(new Runnable() {
//                @Override
//                public void run() {
                    try {
                        Log.d("downloadPhoto", "allPath::" + urlPath);
                        URL url = new URL(urlPath);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setRequestMethod("GET");
                        conn.setConnectTimeout(5 * 1000);
                        conn.connect();
                        InputStream in = conn.getInputStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len = 0;
                        while ((len = in.read(buffer)) != -1) {
                            bos.write(buffer, 0, len);
                        }
                        dataImage = bos.toByteArray();
                        bos.close();
                        in.close();

                        Log.v("downloadPhoto", "dataImage.length::" + dataImage.length);
                        if (dataImage.length > 1024) {
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = false;
                            options.inSampleSize = 2;
                            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                            bitmap = BitmapFactory.decodeByteArray(dataImage, 0, dataImage.length, options);
                        } else {

                            bitmap = BitmapFactory.decodeByteArray(dataImage, 0, dataImage.length);
                        }
                        saveBitmap(file, bitmap, name);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
//
//                }
//            });



            return bitmap;

        } catch (Exception e) {
            Log.d("downloadPhoto", "下载异常");
            e.printStackTrace();
            return null;

        }


    }

    /**
     * 保存图片到内存卡
     */
    private void saveBitmap(File file, Bitmap obj, String name) {
        Log.d("downloadPhoto", "saveBitmap::file::" + file.getPath());

        File imageFile = new File(MyBitmapUtil.PHOTO_DIR,name);
        File file2 = MyBitmapUtil.PHOTO_DIR;

        if (!file2.exists()) {
            file2.mkdirs();
        }
        try {
            imageFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(imageFile);
            //  压缩0-100.100位原质量大小
            obj.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
            Log.d("downloadPhoto", "saveBitmap::保存成功file::" + file.getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 处理头像图片地址
     */

    public Bitmap downloadPhotoAva(int MemberId, String name) {
        try {
            File file = MyBitmapUtil.PHOTO_DIR;
            if (!file.exists()) {
                file.mkdirs();
            }
//            Log.v("downloadPhotoAva", "name::" + name);
            String[] str = name.split("/");
            String rename;
            rename = str[str.length - 1];
//            Log.v("downloadPhotoAva", "name::" + rename);
            File file1 = new File(file + "/" + rename);
            if (file1.exists()) {
                return null;
            } else {
                if (file1.length() == 0)
                    file1.delete();

                return downloadPhoto(file, downUrl + MemberId + "/" + rename, rename);

            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 重写下载头像方法
    public Bitmap re_downloadPhoto(String urlPath, String name) {
        File file = MyBitmapUtil.PHOTO_DIR;
        if (!file.exists()) {
            file.mkdir();
        }
        File file2 = new File(file + "/" + name);
        if (file2.exists()) {
            return null;
        } else {
            Log.d("test", "不存在图片，开始下载");
            return downloadPhoto(file, urlPath, name);
        }
    }

}
